import * as jwt from "jsonwebtoken";
import { JWT_SECRET_KEY } from "@/config";
import Response from "@common/Response";

const verifyToken = async (authorization: string) => {
  try {
    const token = authorization.replace("Bearer ", "");
    const user = jwt.verify(token, JWT_SECRET_KEY);
    return user;
  } catch (err) {
    switch (err.name) {
      case "TokenExpiredError":
        throw Response.Error(4001, "token已过期");
      case "JsonWebTokenError":
        throw Response.Error(4002, "无效的token");
      default:
        throw Response.Error(4003, "鉴权失败");
    }
  }
};

export default verifyToken;
